<template>
  <div class="personal-center">
    <!-- 返回按钮 -->
    <div class="back-btn-container">
      <el-button type="text" @click="handleBack" class="back-btn">
        <el-icon><ArrowLeft /></el-icon> 返回
      </el-button>
    </div>

    <!-- 头部信息及头像上传 -->
    <div class="header">
      <el-upload
        class="avatar-uploader"
        action="#"
        :show-file-list="false"
        :on-change="handleAvatarChange"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="teacherInfo.imgPath" :src="teacherInfo.imgPath" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div class="info">
        <span class="name">{{ userStore.teacherinfo.teacherName }}</span>
        <span class="role">{{ roleMap[teacherInfo.role] }}</span>
      </div>
    </div>

    <!-- 表单信息编辑 -->
    <el-form :model="teacherInfo" label-width="120px" class="form">
      <el-form-item label="教师ID">
        <el-input v-model="teacherInfo.teacherId" disabled />
      </el-form-item>
      <el-form-item label="教师姓名">
        <el-input v-model="teacherInfo.teacherName" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="teacherInfo.password" type="text" />
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="teacherInfo.telephone" />
      </el-form-item>
      <el-form-item label="角色">
        <el-input :value="roleMap[teacherInfo.role]" disabled />
      </el-form-item>
      <el-form-item label="创建人">
        <el-input :value="teacherInfo.createName" disabled />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-input :value="teacherInfo.createTime" disabled />
      </el-form-item>
      <el-form-item label="修改人">
        <el-input :value="teacherInfo.amendName" disabled />
      </el-form-item>
      <el-form-item label="修改时间">
        <el-input :value="teacherInfo.amendTime" disabled />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElUpload, ElIcon, ElInput, ElForm, ElFormItem, ElButton, ElMessage } from 'element-plus'
import { Plus, ArrowLeft } from '@element-plus/icons-vue'
import router from '@/router' // 引入路由实例
import { TeacherInfo } from '@/stores/counter'
import api from '@/api/teacher'
import log from '@/api/log'
import defaultAvatar from '@/assets/default.jpg'
import axios from 'axios'
const userStore = TeacherInfo()

// 模拟角色映射
const roleMap = {
  1: '超级管理员',
  2: '讲师',
}

const imginfo = ref({
  imgPath: '',
  teacherName: '',
})

const teacherInfo = ref({
  teacherId: '',
  teacherName: '',
  password: '',
  telephone: '',
  role: '',
  imgPath: defaultAvatar,
  code: '',
  createName: '',
  createTime: '',
  amendName: '',
  amendTime: '',
})


// 头像上传相关方法
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const handleAvatarChange = async (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    teacherInfo.value.imgPath = e.target.result
  }
  reader.readAsDataURL(file.raw)

  imginfo.value.imgPath = file.raw // 存储原始文件对象
  imginfo.value.teacherName = userStore.teacherinfo.teacherName
  try {
    const formData = new FormData()
    formData.append('file', imginfo.value.imgPath)
    formData.append('teacherName', imginfo.value.teacherName)
    const res = await api.uploadFile(formData) // 调用上传接口
    if (res.code === 200) {
      teacherInfo.value.imgPath = res.data.imgPath // 更新头像地址为后端返回的地址
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error(res.msg || '头像上传失败')
    }
  } catch (error) {
    ElMessage.error('头像上传出错，请重试')
    console.error('头像上传失败：', error)
  }
}

// 保存个人信息
// const handleSave = () => {
//   // teacherInfo.value.amendName = userStore.teacherinfo.teacherName;
//   try {
//     const res = api.update(teacherInfo.value)
//     if (res != null) {
//       // 成功处理：检查业务状态码
//       try {
//         // 更改登录信息
//         const res = log.updateTLogin({
//           loginName: userStore.teacherinfo.teacherName,
//           updateName: teacherInfo.value.teacherName,
//         })
//         if (res != null) {
//           userStore.teacherinfo.teacherName = teacherInfo.value.teacherName
//           console.log('userStore.teacherinfo.teacherName' + userStore.teacherinfo.teacherName)
//           localStorage.setItem('token', JSON.stringify(userStore.teacherinfo))
//           ElMessage.success('保存成功')

//           router.push('/back')
//         }
//       } catch {
//         ;(error) => {
//           // 更改登录信息异常
//           console.error('更新用户信息失败:', error)
//           ElMessage.error('登录信息修改失败')
//         }
//       }
//     }
//   } catch {
//     ;(error) => {
//       // 更改用户信息异常
//       console.error('更新登录信息失败:', error)
//       ElMessage.error('该用户名或手机号已经被使用')
//     }
//   }
// }

const handleSave = async () => {
  try {
    // 1. 调用更新用户信息API（假设为异步操作）
    const updateRes = await api.update(teacherInfo.value);
    
    if (updateRes && updateRes.code==200) {
      // 2. 调用更新登录信息API
      const loginRes = await log.updateTLogin({
        loginName: userStore.teacherinfo.teacherName,
        updateName: teacherInfo.value.teacherName,
      });
      
      if (loginRes && loginRes.code==200) {
        // 3. 成功逻辑
        userStore.teacherinfo.teacherName = teacherInfo.value.teacherName;
        localStorage.setItem('token', JSON.stringify(userStore.teacherinfo));

             
        location.reload();
        ElMessage.success('保存成功'); 
      } else {
        // 登录信息更新失败
        throw new Error('登录信息更新失败');
      }
    } else {
      // 用户信息更新失败
      throw new Error('用户信息更新失败');
    }
  } catch (error) {
    // 统一错误处理
    console.error('操作失败:', error);
    ElMessage.error('该用户名或手机号已经存在');
  }
}

// 返回上一个路由
const handleBack = () => {
  // router.push('/back') 
  router.back()
}

const getteacherinfo = async () => {
  try {
    const res = await api.findTeacherByName({
      teacherName: userStore.teacherinfo.teacherName,
    })
    // 如果后端返回的头像地址为空，使用默认头像，否则使用后端返回的地址
    teacherInfo.value = res
    //TemporarilyStoreData.value = res
    if (!teacherInfo.value.imgPath) {
      teacherInfo.value.imgPath = defaultAvatar
    }
  } catch (error) {
    console.error('调用失败:', error)
  }
}

onMounted(() => {
  getteacherinfo()
})
</script>

<style scoped>
.personal-center {
  padding: 20px;
  position: relative;
}

/* 返回按钮样式 */
.back-btn-container {
  position: absolute;
  top: 20px;
  right: 20px;
}

.back-btn {
  color: #606266; /* 灰色文字 */
  font-size: 14px;
  display: flex;
  align-items: center;
}

.back-btn:hover {
  color: #909399; /* 鼠标悬停时颜色变浅 */
}

.header {
  display: flex;
  align-items: center;
  margin: 30px 0;
}

.avatar-uploader {
  margin-right: 20px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}

.avatar-uploader-icon {
  font-size: 48px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  background-color: #fbfbfb;
}

.info {
  display: flex;
  flex-direction: column;
}

.name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
}

.role {
  color: #666;
}

.form {
  width: 600px;
}
</style>
